const express = require('express')
const database = require('../../database')

const router = express.Router()

router.post('/updatePassword', async (request, response) => {
    const username = request.auth.username
    const info = request.body
    let sql = 'select * from user where username = ?'
    let allowed = await new Promise(resolve => {
        database.query(sql, [username], (error, result) => {
            if(error) {
                response.status(417).end()
            } else {
                resolve(result[0].password == info.oldPassword)
            }
        })
    })
    if(allowed) {
        sql = 'update user set password = ? where username = ?'
        database.query(sql, [username, info.newPassword], (error, request) => {
            if(error) {
                response.status(417).end()
            } else {
                response.send({allowed})
            }
        })
    } else {
        response.send({allowed})
    }
})

module.exports = router